<template>
  <div class="chat-container">
    <!-- 左侧侧边栏 -->
    <div class="chat-sidebar">
      <!-- 最近对话区域 -->
      <div class="recent-section">
        <div class="section-header">
          <h3>最近对话</h3>
        </div>
        <div class="recent-roles">
          <div
            v-for="role in recentRoles"
            :key="role.roleId"
            :class="['role-item', { active: currentRole?.roleId === role.roleId }]"
            @click="switchToRole(role)"
          >
            <el-avatar :size="40" :src="role.image">
              {{ role.roleName?.charAt(0) }}
            </el-avatar>
            <div class="role-info">
              <div class="role-name">{{ role.roleName }}</div>
              <div class="role-source">{{ role.source }}</div>
            </div>
            <div class="role-actions">
              <el-button
                v-if="currentRole?.roleId === role.roleId"
                size="small"
                type="primary"
                circle
              >
                <el-icon><Check /></el-icon>
              </el-button>
              <el-button
                size="small"
                type="text"
                @click="removeFromRecentRoles(role.roleId, $event)"
              >
                <el-icon><Close /></el-icon>
              </el-button>
            </div>
          </div>
          <div v-if="recentRoles.length === 0" class="empty-state">
            <el-icon size="40" color="#ccc"><ChatDotRound /></el-icon>
            <p>暂无对话记录</p>
          </div>
        </div>
      </div>
      
      <!-- 聊天记录区域 -->
      <div class="records-section">
        <div class="section-header">
          <h3>聊天记录</h3>
          <el-button 
            size="small" 
            type="primary" 
            @click="refreshChatRecords"
            :loading="loadingRecords"
          >
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
        <div class="chat-records">
          <div
            v-for="record in chatRecords"
            :key="record.memoryId"
            :class="['record-item', { active: memoryId === record.memoryId }]"
            @click="loadChatRecord(record)"
          >
            <el-avatar :size="40" :src="record.roleImage">
              {{ record.roleName?.charAt(0) }}
            </el-avatar>
            <div class="record-info">
              <div class="record-role">{{ record.roleName }}</div>
              <div class="record-preview">{{ record.lastMessage || '暂无消息' }}</div>
              <div class="record-time">{{ formatRecordTime(record.updateTime) }}</div>
            </div>
            <div class="record-actions">
              <el-button
                size="small"
                type="text"
                @click="deleteChatRecord(record.memoryId, $event)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
          <div v-if="chatRecords.length === 0 && !loadingRecords" class="empty-state">
            <el-icon size="40" color="#ccc"><ChatDotRound /></el-icon>
            <p>暂无聊天记录</p>
          </div>
          <div v-if="loadingRecords" class="loading-state">
            <el-icon class="is-loading" size="20"><Loading /></el-icon>
            <p>加载中...</p>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 主聊天区域 -->
    <div class="chat-main">
      <div class="chat-header">
      <div class="role-info">
        <el-popover
          v-if="currentRole"
          placement="bottom-start"
          :width="300"
          trigger="click"
        >
          <template #reference>
            <el-avatar :size="50" :src="currentRole?.image" style="cursor: pointer">
              {{ currentRole?.roleName?.charAt(0) }}
            </el-avatar>
          </template>
          <div class="role-popover">
            <div class="role-popover-header">
              <el-avatar :size="60" :src="currentRole?.image">
                {{ currentRole?.roleName?.charAt(0) }}
              </el-avatar>
              <div class="role-popover-info">
                <h3>{{ currentRole?.roleName }}</h3>
                <p class="role-source">{{ currentRole?.source }}</p>
                <el-tag :type="getStatusType(currentRole?.status)" size="small">
                  {{ getStatusName(currentRole?.status) }}
                </el-tag>
              </div>
            </div>
            <div class="role-popover-details">
              <div v-if="currentRole?.personality" class="detail-item">
                <strong>性格特点：</strong>
                <p>{{ currentRole.personality }}</p>
              </div>
              <div v-if="currentRole?.languageStyle" class="detail-item">
                <strong>语言风格：</strong>
                <p>{{ currentRole.languageStyle }}</p>
              </div>
              <div v-if="currentRole?.backgroundKnowledge" class="detail-item">
                <strong>背景知识：</strong>
                <p>{{ currentRole.backgroundKnowledge }}</p>
              </div>
            </div>
          </div>
        </el-popover>
        <el-avatar v-else :size="50" :src="currentRole?.image">
          {{ currentRole?.roleName?.charAt(0) }}
        </el-avatar>
        <div class="role-details">
          <h3>{{ currentRole?.roleName || '选择角色' }}</h3>
          <p>{{ currentRole?.source || '请先选择一个角色开始聊天' }}</p>
        </div>
      </div>
      <div class="chat-actions">
        <el-button @click="clearChat">清空对话</el-button>
        <el-upload
          :show-file-list="false"
          :before-upload="beforeUploadVoice"
          :http-request="handleCustomUpload"
          accept="audio/*"
        >
          <el-button>上传语音</el-button>
        </el-upload>
        <el-button type="primary" @click="goToRoles">选择角色</el-button>
      </div>
    </div>
    
    <div class="chat-content">
      <!-- 角色选择区域 -->
      <div v-if="!currentRole" class="role-selection">
        <h2>选择一个角色开始聊天</h2>
        <div class="role-grid">
          <div
            v-for="role in availableRoles"
            :key="role.roleId"
            class="role-card"
            @click="selectRole(role)"
          >
            <el-avatar :size="60" :src="role.image">
              {{ role.roleName.charAt(0) }}
            </el-avatar>
            <h4>{{ role.roleName }}</h4>
            <p>{{ role.source }}</p>
            <el-tag :type="getStatusType(role.status)" size="small">
              {{ getStatusName(role.status) }}
            </el-tag>
          </div>
        </div>
      </div>
      
      <!-- 聊天区域 -->
      <div v-else class="chat-messages">
        <div ref="messagesContainer" class="messages-container">
          <div
            v-for="message in messages"
            :key="message.id"
            :class="['message', message.type]"
          >
            <div class="message-avatar">
              <el-avatar :size="40" :src="message.type === 'user' ? userAvatar : currentRole?.image">
                {{ message.type === 'user' ? '我' : currentRole?.roleName?.charAt(0) }}
              </el-avatar>
            </div>
            <div class="message-content">
              <div class="message-text" v-html="formatMessage(message.content)"></div>
              <div class="message-footer">
                <div class="message-header">
                  <span class="sender">{{ message.type === 'user' ? '我' : currentRole?.roleName }}</span>
                </div>
                <div class="message-actions">
                  <el-button
                    v-if="message.type === 'ai'"
                    size="small"
                    type="text"
                    :loading="message.ttsLoading"
                    @click="playTTS(message)"
                  >
                    <el-icon><VideoPlay /></el-icon>
                    播放
                  </el-button>
                </div>
              </div>
            </div>
          </div>
          
          <!-- 加载中提示 -->
          <div v-if="isLoading" class="message ai">
            <div class="message-avatar">
              <el-avatar :size="40" :src="currentRole?.image">
                {{ currentRole?.roleName?.charAt(0) }}
              </el-avatar>
            </div>
            <div class="message-content">
              <div class="message-text">
                <el-icon class="is-loading"><Loading /></el-icon>
                {{ currentRole?.roleName }}正在思考中...
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 输入区域 -->
    <div v-if="currentRole" class="chat-input">
      <el-input
        v-model="inputMessage"
        type="textarea"
        :rows="3"
        placeholder="输入你的消息..."
        :disabled="isLoading"
        @keydown.enter.exact.prevent="sendMessage"
        @keydown.enter.shift.exact="inputMessage += '\n'"
      />
      <div class="input-actions">
        <el-button
          :type="isRecording ? 'danger' : 'default'"
          :loading="recordingBusy"
          @click="toggleRecording"
        >
          {{ isRecording ? '停止录音并上传' : '录音上传' }}
        </el-button>
        <el-button
          type="primary"
          :loading="isLoading"
          :disabled="!inputMessage.trim()"
          @click="sendMessage"
        >
          发送
        </el-button>
      </div>
    </div>
    </div>
    
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useRoleStore } from '@/stores/role'
import { useUserStore } from '@/stores/user'
import { chatWithAI } from '@/api/chat'
import { uploadFile, translateAudio, getAudioUrl } from '@/api/media'
import { getChatMessageList, getChatMessageByMemoryId, deleteChatMessage } from '@/api/chatMessage'
import { ElMessage, ElMessageBox } from 'element-plus'

const route = useRoute()
const router = useRouter()
const roleStore = useRoleStore()
const userStore = useUserStore()

// 响应式数据
const currentRole = ref(null)
const availableRoles = ref([])
const recentRoles = ref([])
const chatRecords = ref([])
const messages = ref([])
const inputMessage = ref('')
const isLoading = ref(false)
const loadingRecords = ref(false)
const messagesContainer = ref()
const memoryId = ref('')
const uploading = ref(false)
const isRecording = ref(false)
const recordingBusy = ref(false)
let mediaRecorder = null
let mediaStream = null
let recordedChunks = []

// 用户头像
const userAvatar = ref('')

// 获取角色列表
const fetchRoles = async () => {
  try {
    await roleStore.fetchRoleList({ page: 1, pageSize: 100, status: 1 })
    availableRoles.value = roleStore.roleList
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

// 选择角色
const selectRole = (role) => {
  currentRole.value = role
  messages.value = []
  memoryId.value = `memory_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  
  // 添加到最近对话列表
  addToRecentRoles(role)
  
  // 添加欢迎消息
  messages.value.push({
    id: Date.now(),
    type: 'ai',
    content: `你好！我是${role.roleName}，很高兴与你聊天！${role.personality ? `我的性格特点是：${role.personality}` : ''}`,
    timestamp: new Date(),
    ttsLoading: false
  })
}

// 添加到最近对话列表
const addToRecentRoles = (role) => {
  // 移除已存在的相同角色
  const index = recentRoles.value.findIndex(r => r.roleId === role.roleId)
  if (index > -1) {
    recentRoles.value.splice(index, 1)
  }
  
  // 添加到列表顶部
  recentRoles.value.unshift(role)
  
  // 限制最多显示10个最近对话
  if (recentRoles.value.length > 10) {
    recentRoles.value = recentRoles.value.slice(0, 10)
  }
  
  // 保存到本地存储
  localStorage.setItem('recentRoles', JSON.stringify(recentRoles.value))
}

// 从最近对话中删除角色
const removeFromRecentRoles = (roleId, event) => {
  event.stopPropagation() // 阻止事件冒泡
  const index = recentRoles.value.findIndex(r => r.roleId === roleId)
  if (index > -1) {
    recentRoles.value.splice(index, 1)
    // 更新本地存储
    localStorage.setItem('recentRoles', JSON.stringify(recentRoles.value))
  }
}

// 从本地存储加载最近对话
const loadRecentRoles = () => {
  try {
    const stored = localStorage.getItem('recentRoles')
    if (stored) {
      recentRoles.value = JSON.parse(stored)
    }
  } catch (error) {
    console.error('加载最近对话失败:', error)
  }
}

// 切换到角色（不改变顺序）
const switchToRole = (role) => {
  currentRole.value = role
  messages.value = []
  memoryId.value = `memory_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  
  // 添加到最近对话列表
  addToRecentRoles(role)
  
  // 添加欢迎消息
  messages.value.push({
    id: Date.now(),
    type: 'ai',
    content: `你好！我是${role.roleName}，很高兴与你聊天！${role.personality ? `我的性格特点是：${role.personality}` : ''}`,
    timestamp: new Date(),
    ttsLoading: false
  })
}


// 获取聊天记录列表
const fetchChatRecords = async () => {
  try {
    loadingRecords.value = true
    const response = await getChatMessageList()
    
    // 检查响应是否成功
    if (response && response.code !== undefined && response.code !== 0) {
      throw new Error(response.msg || '获取聊天记录失败')
    }
    
    // 处理响应数据
    const records = response && response.data !== undefined ? response.data : response
    
    // 处理记录数据，映射为前端需要的格式
    if (records && records.roleInfos && records.memoryIds) {
      chatRecords.value = records.roleInfos.map((role, index) => {
        // 找到对应的memoryId
        const memoryId = records.memoryIds[index] || records.memoryIds[0] || `memory_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
        
        // 提取最后一条消息作为预览
        let lastMessage = '点击查看详情'
        if (role.personality) {
          lastMessage = `性格特点：${role.personality.substring(0, 20)}${role.personality.length > 20 ? '...' : ''}`
        }
        
        return {
          memoryId: memoryId,
          roleId: role.roleId,
          roleName: role.roleName,
          roleImage: role.image,
          roleSource: role.source,
          rolePersonality: role.personality,
          roleLanguageStyle: role.languageStyle,
          roleBackgroundKnowledge: role.backgroundKnowledge,
          roleStatus: role.status,
          updateTime: role.updateTime || new Date().toISOString(),
          lastMessage: lastMessage
        }
      })
    } else {
      chatRecords.value = []
    }
  } catch (error) {
    console.error('获取聊天记录失败:', error)
    ElMessage.error('获取聊天记录失败: ' + (error.message || error))
    chatRecords.value = [] // 确保在出错时也清空记录列表
  } finally {
    loadingRecords.value = false
  }
}

// 刷新聊天记录
const refreshChatRecords = () => {
  fetchChatRecords()
}

// 加载特定聊天记录
const loadChatRecord = async (record) => {
  try {
    console.log('开始加载聊天记录:', record)
    memoryId.value = record.memoryId
    currentRole.value = {
      roleId: record.roleId,
      roleName: record.roleName,
      image: record.roleImage,
      source: record.roleSource,
      personality: record.rolePersonality,
      languageStyle: record.roleLanguageStyle,
      backgroundKnowledge: record.roleBackgroundKnowledge,
      status: record.roleStatus
    }
    
    console.log('设置当前角色:', currentRole.value)
    // 添加到最近对话列表
    addToRecentRoles(currentRole.value)
    
    // 获取详细聊天记录
    console.log('开始获取详细聊天记录，memoryId:', record.memoryId)
    const response = await getChatMessageByMemoryId(record.memoryId)
    console.log('获取详细聊天记录响应:', response)
    
    // 检查响应是否成功
    if (response.code !== 0) {
      throw new Error(response.msg || '加载聊天记录失败')
    }
    
    const chatMessage = response.data
    console.log('聊天记录数据:', chatMessage)
    
    if (chatMessage && chatMessage.content) {
      // 解析聊天内容
      try {
        console.log('开始解析聊天内容:', chatMessage.content)
        const parsedMessages = parseChatContent(chatMessage.content)
        console.log('解析后的消息列表:', parsedMessages)
        messages.value = parsedMessages
      } catch (parseError) {
        console.error('解析聊天内容失败:', parseError)
        // 如果解析失败，按普通文本处理
        messages.value = [{
          id: Date.now(),
          type: 'ai',
          content: chatMessage.content,
          timestamp: new Date(chatMessage.createTime)
        }]
      }
    } else {
      console.log('没有聊天内容，添加欢迎消息')
      // 没有聊天内容，添加欢迎消息
      messages.value = [{
        id: Date.now(),
        type: 'ai',
        content: `你好！我是${currentRole.value.roleName}，很高兴与你聊天！${currentRole.value.personality ? `我的性格特点是：${currentRole.value.personality}` : ''}`,
        timestamp: new Date(),
        ttsLoading: false
      }]
    }
    
    console.log('最终消息列表:', messages.value)
    scrollToBottom()
  } catch (error) {
    console.error('加载聊天记录失败:', error)
    ElMessage.error('加载聊天记录失败: ' + (error.message || error))
    // 出错时也添加欢迎消息
    if (currentRole.value) {
      messages.value = [{
        id: Date.now(),
        type: 'ai',
        content: `你好！我是${currentRole.value.roleName}，很高兴与你聊天！${currentRole.value.personality ? `我的性格特点是：${currentRole.value.personality}` : ''}`,
        timestamp: new Date(),
        ttsLoading: false
      }]
    } else {
      messages.value = []
    }
    console.log('错误情况下的消息列表:', messages.value)
    scrollToBottom()
  }
}

// 解析聊天内容
const parseChatContent = (contentData) => {
  console.log('开始解析聊天内容，原始数据:', contentData)
  const messages = []
  let messageId = Date.now()
  
  try {
    // 如果是字符串，尝试解析为JSON
    if (typeof contentData === 'string') {
      // 尝试解析为JSON
      try {
        contentData = JSON.parse(contentData)
        console.log('解析为JSON后的数据:', contentData)
      } catch (e) {
        // 如果不是JSON格式，按普通文本处理
        console.log('内容不是JSON格式，按普通文本处理')
        messages.push({
          id: messageId++,
          type: 'ai',
          content: contentData,
          timestamp: new Date()
        })
        return messages
      }
    }
    
    // 如果是数组，表示包含多轮对话
    if (Array.isArray(contentData)) {
      console.log('处理数组格式的聊天内容')
      contentData.forEach((item, index) => {
        console.log(`处理第${index}项:`, item)
        if (item.type === 'USER') {
          // 用户消息
          const userContents = item.contents || []
          console.log('处理用户消息内容:', userContents)
          userContents.forEach(content => {
            if (content.type === 'TEXT') {
              messages.push({
                id: messageId++,
                type: 'user',
                content: content.text,
                timestamp: new Date()
              })
            }
          })
        } else if (item.type === 'AI' || item.type === 'ASSISTANT') {
          // AI消息
          console.log('处理AI消息:', item)
          messages.push({
            id: messageId++,
            type: 'ai',
            content: item.text || item.content || '',
            timestamp: new Date()
          })
        } else if (item.type === 'SYSTEM') {
          // 系统消息（通常不需要显示给用户）
          // 可以选择忽略或特殊处理
          console.log('处理系统消息:', item)
        }
      })
    } else if (typeof contentData === 'object') {
      console.log('处理对象格式的聊天内容')
      // 处理单条消息的不同格式
      if (contentData.contents) {
        // 包含contents字段的情况
        console.log('处理contents字段:', contentData.contents)
        contentData.contents.forEach(content => {
          if (content.type === 'TEXT') {
            messages.push({
              id: messageId++,
              type: contentData.type === 'USER' ? 'user' : 'ai',
              content: content.text,
              timestamp: new Date()
            })
          }
        })
      } else if (contentData.text) {
        // 直接包含text字段的情况
        console.log('处理text字段:', contentData.text)
        messages.push({
          id: messageId++,
          type: contentData.type === 'USER' ? 'user' : 'ai',
          content: contentData.text,
          timestamp: new Date()
        })
      } else if (contentData.content) {
        // 包含content字段的情况
        console.log('处理content字段:', contentData.content)
        messages.push({
          id: messageId++,
          type: contentData.type === 'USER' ? 'user' : 'ai',
          content: contentData.content,
          timestamp: new Date()
        })
      }
    }
    console.log('最终解析的消息列表:', messages)
  } catch (error) {
    console.error('解析聊天内容时出错:', error)
    // 如果解析失败，将原始内容作为单条AI消息
    messages.push({
      id: messageId++,
      type: 'ai',
      content: typeof contentData === 'string' ? contentData : JSON.stringify(contentData),
      timestamp: new Date()
    })
  }
  
  return messages
}

// 删除聊天记录
const deleteChatRecord = async (recordMemoryId, event) => {
  event.stopPropagation()
  
  try {
    await ElMessageBox.confirm('确定要删除这个聊天记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里需要调用删除接口，暂时只从前端移除
    const index = chatRecords.value.findIndex(r => r.memoryId === recordMemoryId)
    if (index > -1) {
      chatRecords.value.splice(index, 1)
    }
    
    // 如果删除的是当前聊天记录，清空消息
    if (memoryId.value === recordMemoryId) {
      messages.value = []
      memoryId.value = ''
      currentRole.value = null
    }
    
    ElMessage.success('聊天记录删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除聊天记录失败:', error)
      ElMessage.error('删除聊天记录失败')
    }
  }
}

// 格式化记录时间
const formatRecordTime = (timestamp) => {
  console.log('格式化时间戳:', timestamp)
  if (!timestamp) return '未知时间'
  
  const date = new Date(timestamp)
  const now = new Date()
  const diff = now - date
  
  if (isNaN(date.getTime())) {
    console.log('无效的时间戳')
    return '无效时间'
  }
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 1天内
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}


// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return
  
  const userMessage = {
    id: Date.now(),
    type: 'user',
    content: inputMessage.value.trim(),
    timestamp: new Date()
  }
  
  messages.value.push(userMessage)
  const messageContent = inputMessage.value.trim()
  inputMessage.value = ''
  
  try {
    isLoading.value = true
    scrollToBottom()
    
    // 调用AI聊天接口
    const response = await chatWithAI(memoryId.value, messageContent, currentRole.value.roleId)
    
    // 添加AI回复
    const aiMessage = {
      id: Date.now() + 1,
      type: 'ai',
      content: response || '抱歉，我现在无法回复你的消息。',
      timestamp: new Date(),
      ttsLoading: false
    }
    
    messages.value.push(aiMessage)
  } catch (error) {
    console.error('发送消息失败:', error)
    ElMessage.error('发送消息失败，请重试')
    
    // 添加错误消息
    const errorMessage = {
      id: Date.now() + 1,
      type: 'ai',
      content: '抱歉，我现在无法回复你的消息，请稍后再试。',
      timestamp: new Date(),
      ttsLoading: false
    }
    
    messages.value.push(errorMessage)
  } finally {
    isLoading.value = false
    nextTick(() => {
      scrollToBottom()
    })
  }
}

// 清空对话
const clearChat = () => {
  messages.value = []
  memoryId.value = `memory_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
  
  if (currentRole.value) {
    // 重新添加欢迎消息
    messages.value.push({
      id: Date.now(),
      type: 'ai',
      content: `你好！我是${currentRole.value.roleName}，很高兴与你聊天！${currentRole.value.personality ? `我的性格特点是：${currentRole.value.personality}` : ''}`,
      timestamp: new Date(),
      ttsLoading: false
    })
  }
}

// 跳转到角色选择
const goToRoles = () => {
  router.push('/roles')
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 格式化时间
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化消息内容
const formatMessage = (content) => {
  // 简单的换行处理
  return content.replace(/\n/g, '<br>')
}

// 获取状态名称
const getStatusName = (status) => {
  const map = { 0: '禁用', 1: '启用', 2: '审核中' }
  return map[status] || '未知'
}

// 获取状态样式
const getStatusType = (status) => {
  const map = { 0: 'danger', 1: 'success', 2: 'warning' }
  return map[status] || ''
}

// 监听路由参数变化
watch(() => route.params.roleId, async (newRoleId) => {
  if (newRoleId) {
    try {
      const role = await roleStore.fetchRoleDetail(newRoleId)
      selectRole(role)
    } catch (error) {
      console.error('获取角色详情失败:', error)
      ElMessage.error('获取角色详情失败')
    }
  }
}, { immediate: true })

onMounted(() => {
  loadRecentRoles()
  fetchChatRecords()
  fetchRoles()
})

// 语音上传前校验
const beforeUploadVoice = (file) => {
  const isAudio = file.type.startsWith('audio/')
  const isLt10M = file.size / 1024 / 1024 < 10
  if (!isAudio) {
    ElMessage.error('仅支持音频文件')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('音频大小需小于10MB')
    return false
  }
  return true
}

// 自定义上传：上传 -> 调用语音转文本 -> 回填到输入框
const handleCustomUpload = async (options) => {
  const { file, onError, onSuccess } = options
  try {
    uploading.value = true
    // 1. 上传文件获取URL
    const fileUrl = await uploadFile(file)
    // 2. 语音转文本
    const text = await translateAudio(fileUrl)
    // 3. 回填到输入框（追加或覆盖，这里采用追加）
    inputMessage.value = (inputMessage.value ? inputMessage.value + '\n' : '') + (text || '')
    ElMessage.success('语音识别完成')
    onSuccess && onSuccess({})
  } catch (e) {
    console.error(e)
    ElMessage.error('语音处理失败')
    onError && onError(e)
  } finally {
    uploading.value = false
  }
}

// 录音功能：点击开始/停止，停止后自动上传
const toggleRecording = async () => {
  if (isRecording.value) {
    await stopRecordingAndUpload()
  } else {
    await startRecording()
  }
}

const startRecording = async () => {
  try {
    recordingBusy.value = true
    mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true })
    const mimeType = MediaRecorder.isTypeSupported('audio/webm') ? 'audio/webm' : ''
    mediaRecorder = new MediaRecorder(mediaStream, mimeType ? { mimeType } : undefined)
    recordedChunks = []
    mediaRecorder.ondataavailable = (e) => {
      if (e.data && e.data.size > 0) recordedChunks.push(e.data)
    }
    mediaRecorder.onstop = () => {
      mediaStream.getTracks().forEach(t => t.stop())
    }
    mediaRecorder.start()
    isRecording.value = true
    ElMessage.success('开始录音')
  } catch (e) {
    console.error('无法开始录音:', e)
    ElMessage.error('无法访问麦克风')
  } finally {
    recordingBusy.value = false
  }
}

const stopRecordingAndUpload = async () => {
  if (!mediaRecorder) return
  try {
    recordingBusy.value = true
    await new Promise(resolve => {
      mediaRecorder.onstop = () => {
        mediaStream && mediaStream.getTracks().forEach(t => t.stop())
        resolve()
      }
      mediaRecorder.stop()
    })

    const blob = new Blob(recordedChunks, { type: 'audio/webm' })
    const file = new File([blob], `recording_${Date.now()}.webm`, { type: 'audio/webm' })
    const fileUrl = await uploadFile(file)
    ElMessage.success('录音上传成功')
    // 自动执行语音转文本并回填到输入框
    const text = await translateAudio(fileUrl)
    inputMessage.value = (inputMessage.value ? inputMessage.value + '\n' : '') + (text || '')
    ElMessage.success('语音识别完成')
  } catch (e) {
    console.error('停止或上传失败:', e)
    ElMessage.error('录音上传失败')
  } finally {
    isRecording.value = false
    mediaRecorder = null
    mediaStream = null
    recordedChunks = []
    recordingBusy.value = false
  }
}

// 播放TTS音频
const playTTS = async (message) => {
  if (!currentRole.value || !message.content) return
  
  try {
    message.ttsLoading = true
    // 获取音频URL
    const audioUrl = await getAudioUrl(
      message.content,
      undefined, // voice参数，使用默认
      undefined, // language参数，使用默认
      currentRole.value.roleId
    )
    
    // 创建音频元素并播放
    const audio = new Audio(audioUrl)
    audio.onended = () => {
      message.ttsLoading = false
    }
    audio.onerror = () => {
      ElMessage.error('音频播放失败')
      message.ttsLoading = false
    }
    await audio.play()
  } catch (error) {
    console.error('TTS播放失败:', error)
    ElMessage.error('语音合成失败')
    message.ttsLoading = false
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  height: 100vh;
  background: #fafbfc;
}

.chat-sidebar {
  width: 280px;
  background: #fff;
  border-right: 1px solid #eee;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #f8f9fa;
}

/* 区域样式 */
.recent-section {
  border-bottom: 1px solid #eee;
  height: 50%;
  min-height: 200px;
}

.records-section {
  height: 50%;
  min-height: 200px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px 10px;
  background: #f8f9fa;
  border-bottom: 1px solid #eee;
}

.section-header h3 {
  margin: 0;
  color: #333;
  font-size: 14px;
  font-weight: 600;
}

.recent-roles {
  overflow-y: auto;
  padding: 5px 0;
  height: calc(100% - 50px);
}

.chat-records {
  overflow-y: auto;
  padding: 5px 0;
  height: calc(100% - 50px);
}

/* 角色项样式 */
.role-item {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  cursor: pointer;
  transition: all 0.3s;
  border-left: 3px solid transparent;
}

.role-item:hover {
  background: #f5f5f5;
}

.role-item.active {
  background: #e6f7ff;
  border-left-color: #409eff;
}

.role-info {
  flex: 1;
  margin-left: 12px;
  min-width: 0;
}

.role-name {
  font-weight: 600;
  color: #333;
  font-size: 13px;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.role-source {
  color: #666;
  font-size: 11px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.role-actions {
  display: flex;
  align-items: center;
  gap: 4px;
  opacity: 0;
  transition: opacity 0.3s;
}

.role-item:hover .role-actions {
  opacity: 1;
}

.role-actions .el-button {
  padding: 4px;
  width: 20px;
  height: 20px;
  min-height: 20px;
}

/* 记录项样式 */
.record-item {
  display: flex;
  align-items: center;
  padding: 10px 20px;
  cursor: pointer;
  transition: all 0.3s;
  border-left: 3px solid transparent;
}

.record-item:hover {
  background: #f5f5f5;
}

.record-item.active {
  background: #e6f7ff;
  border-left-color: #409eff;
}

.record-info {
  flex: 1;
  margin-left: 12px;
  min-width: 0;
}

.record-role {
  font-weight: 600;
  color: #333;
  font-size: 13px;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.record-preview {
  color: #666;
  font-size: 11px;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.record-time {
  color: #999;
  font-size: 10px;
}

.record-actions {
  display: flex;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.record-item:hover .record-actions {
  opacity: 1;
}

.record-actions .el-button {
  padding: 4px;
  width: 20px;
  height: 20px;
  min-height: 20px;
}

.role-name {
  font-weight: 600;
  color: #333;
  font-size: 14px;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.role-source {
  color: #666;
  font-size: 12px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #999;
}

.empty-state p {
  margin: 10px 0 0 0;
  font-size: 14px;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
  color: #999;
}

.loading-state p {
  margin: 10px 0 0 0;
  font-size: 14px;
}


.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  background: #fff;
  border-bottom: 1px solid #eee;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.role-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.role-details h3 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.role-details p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.chat-actions {
  display: flex;
  gap: 10px;
}

.chat-content {
  flex: 1;
  overflow: hidden;
}

.role-selection {
  padding: 40px;
  text-align: center;
}

.role-selection h2 {
  color: #333;
  margin-bottom: 30px;
  font-size: 24px;
  font-weight: 600;
}

.role-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.role-card {
  background: #fff;
  border-radius: 12px;
  padding: 20px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.role-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
}

.role-card h4 {
  margin: 10px 0 5px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.role-card p {
  margin: 0 0 10px 0;
  color: #666;
  font-size: 14px;
}

.chat-messages {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px 30px;
}

.message {
  display: flex;
  margin-bottom: 20px;
  gap: 15px;
}

.message.user {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  flex: 1;
  max-width: 70%;
  min-width: 0;
}

.message.user .message-content {
  text-align: right;
}

.message-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 8px;
}

.message.user .message-footer {
  flex-direction: row-reverse;
}

.message-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.sender {
  font-weight: 600;
  color: #333;
  font-size: 14px;
}

.time {
  color: #999;
  font-size: 12px;
}

.message-text {
  background: #fff;
  padding: 12px 16px;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  line-height: 1.6;
  color: #333;
  display: inline-block;
  max-width: 100%;
  word-wrap: break-word;
  word-break: break-word;
  border: 1px solid #f0f0f0;
}

.message.user .message-text {
  background: #6c7ce7;
  color: #fff;
  border: none;
}

.message.ai .message-text {
  background: #fff;
  border: 1px solid #eee;
}

.chat-input {
  padding: 20px 30px;
  background: #fff;
  border-top: 1px solid #eee;
}

.input-actions {
  margin-top: 10px;
  text-align: right;
}

:deep(.el-textarea__inner) {
  border-radius: 12px;
  border: 1px solid #ddd;
  resize: none;
}

:deep(.el-textarea__inner:focus) {
  border-color: #409eff;
}

/* 滚动条样式 */
.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 角色信息弹窗样式 */
.role-popover {
  padding: 0;
}

.role-popover-header {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.role-popover-info h3 {
  margin: 0 0 5px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.role-source {
  margin: 0 0 8px 0;
  color: #666;
  font-size: 14px;
}

.role-popover-details {
  padding: 15px;
}

.detail-item {
  margin-bottom: 12px;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-item strong {
  color: #333;
  font-size: 13px;
  display: block;
  margin-bottom: 4px;
}

.detail-item p {
  margin: 0;
  color: #666;
  font-size: 13px;
  line-height: 1.4;
  word-break: break-word;
}

/* 消息操作按钮样式 */
.message-actions {
  display: flex;
  align-items: center;
}

.message-actions .el-button {
  padding: 4px 8px;
  font-size: 12px;
  height: auto;
  min-height: 24px;
}
</style>
